package com.yeyks.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.yeyks.common.appcommon.result.CommonResult;
import com.yeyks.common.appcommon.result.Ret;
import com.yeyks.common.exception.OftenFiledException;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
//import org.springframework.boot.autoconfigure.web.BasicErrorController;
//import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Administrator
 */
@RestController
@Api(value = "filter错误处理", description = "filter错误处理")
public class ErrorController extends BasicErrorController {

    public ErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        //自定义的错误信息类
        String jsonCommonResult = body.get("message").toString();
        Ret ret = null;
        if(!StringUtils.isEmpty(jsonCommonResult)) {
            CommonResult commonResult = JSONObject.parseObject(jsonCommonResult, CommonResult.class);
            ret = Ret.error(commonResult.getCode(), commonResult.getMsg());
        }
        //OftenFiledException Filter抛出的自定义错误类
        if (!Strings.isNullOrEmpty((String) body.get("com/yeyks/exception")) && body.get("com/yeyks/exception").equals(OftenFiledException.class.getName())) {
            body.put("status", HttpStatus.FORBIDDEN.value());
            status = HttpStatus.FORBIDDEN;
        }
        return new ResponseEntity(ret, status);
    }


    @Override
    public String getErrorPath() {
        return super.getErrorPath();
    }
}
